package com.cg.leetcode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 429.N 叉树的层序遍历
 *
 * @program: LeetCode->LeetCode_429
 * @author: cg
 * @create: 2022-04-19 20:30
 **/
public class LeetCode_429 {

    @Test
    public void test429() {
        Node root = new Node(1);
        root.neighbors = new ArrayList<>();
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        root.neighbors.add(node3);
        root.neighbors.add(node2);
        root.neighbors.add(node4);
        node3.neighbors = new ArrayList<>();
        node3.neighbors.add(node5);
        node3.neighbors.add(node6);
        System.out.println(levelOrder(root));
    }

    /**
     * 给定一个 N 叉树，返回其节点值的层序遍历。（即从左到右，逐层遍历）。
     * <p>
     * 树的序列化输入是用层序遍历，每组子节点都由 null 值分隔（参见示例）。
     * <p>
     * 示例 1：
     * 输入：root = [1,null,3,2,4,null,5,6]
     * 输出：[[1],[3,2,4],[5,6]]
     * <p>
     * 示例 2：
     * 输入：root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
     * 输出：[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
     * <p>
     * 提示：
     * 树的高度不会超过 1000
     * 树的节点总数在 [0, 10^4] 之间
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Node> queue = new LinkedList<>();
        if (root == null) {
            return res;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Node node = queue.remove();
                list.add(node.val);
                List<Node> neighbors = node.neighbors;
                queue.addAll(neighbors);
            }
            res.add(list);
        }
        return res;
    }

}
